package com.gaosai.staff.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.answer_staff.R;



/**
 * 公共的工具类
 * @author willis
 *
 */
public class CommonUtils {


	/**
	 * 显示软件盘的方法，这里要采用延时操作，不然会显示不了软键盘。主要是登录，注册时一进去就自动弹出键盘。
	 */
	public static void showSoft(final EditText editText) {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				InputMethodManager inputManager = (InputMethodManager) editText
						.getContext().getSystemService(
								Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(editText, 0);
			}
		}, 50);
	}

	// 快速显示键盘的方法，引用回复的时候回复按钮一点弹出键盘就用这个方法。
	public static void ShowSoftFast(Context context) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		View view = ((Activity) context).getCurrentFocus();
		if (view != null) {
			imm.showSoftInput(view, 0); // 显示软键盘
		}
	}

	/**
	 * 隐藏软键盘的方法
	 * 
	 * @param context
	 *            要传入的上下文
	 */
	public static void hiddenSoft(Context context) {
		// 取得输入方法的服务类
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		View view = ((Activity) context).getCurrentFocus();
		if (view != null) {
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);// 隐藏软键盘

		}
	}

	// 快速隐藏键盘
	public static void hideSoftQuick(Activity context) {
		((InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE))
				.hideSoftInputFromWindow(context.getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}


	/***
	 * 隐藏键盘
	 * @Description:TODO
	 * @param context
	 */

	public static void hideIme(Activity context) {
		if (context == null)
			return;
		final View v = context.getWindow().peekDecorView();
		if (v != null && v.getWindowToken() != null) {
			InputMethodManager imm = (InputMethodManager) context
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		}
	}

	/***
	 * 键盘是否打开
	 * @Description:TODO
	 * @param context
	 * @return
	 */
	public static boolean isImeShow(Context context) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		return imm.isActive();
	}

	/***
	 * 判断是否有sd卡
	 * @Description:TODO
	 * @return
	 */
	public static boolean ExistSDCard() {  
		if (android.os.Environment.getExternalStorageState().equals(  
				android.os.Environment.MEDIA_MOUNTED)) {  
			return true;  
		} else  
			return false;  
	} 

	/**
	 * 取得arrays.xml中的数据以数组的形式返回
	 * @param context  上下文
	 * @param arrays   arrays.xml文件中的 string-name的名字
	 * @return
	 */
	public static String[] getStringFormArrays(Context context,int arrayres){
		Resources res = context.getResources();
		return res.getStringArray(arrayres); 
	}

	/**
	 * MD5加密算法
	 * 
	 * @param str
	 * @return
	 */
	public static String toMD5(String str) {
		try {
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(str.getBytes("UTF-8"));
			return toHexString(algorithm.digest());
		} catch (NoSuchAlgorithmException e) {
			Log.v("MD5", "toMd5(): " + e);
			throw new RuntimeException(e);
		} catch (UnsupportedEncodingException e) {
			Log.v("MD5", "toMd5(): " + e);
		}
		return "";
	}
	private static String toHexString(byte[] bytes) {
		StringBuilder hexString = new StringBuilder();
		for (byte b : bytes) {
			hexString.append(Integer.toHexString(0xFF & b));
		}
		return hexString.toString();
	}


	/**
	 * 取得应用程序的版本名字
	 * @Methods: getAppVersionName
	 * @param context 上下文
	 * @return 返回当前程序版本名
	 * @throws
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// 取得包信息
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionName;
	}


	/**
	 * 取得应用程序的版本号
	 * @Methods: getAppVersionCode
	 * @param context 上下文
	 * @return 返回当前程序版本code
	 * @throws
	 */
	public static int getAppVersionCode(Context context) {
		int versionCode = 0 ;
		try {
			// 取得包信息
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionCode = pi.versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionCode;
	}
	/**创建选择对话框*/
	private static Dialog mDialog ;
	public static void createSelectDialog(Context context,String title,String[] strs, DialogInterface.OnClickListener listener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context) ;
		builder.setTitle(title);
		builder.setItems(strs,listener) ;
		mDialog = builder.create() ;
		mDialog.show() ;
	}
	/**让选择对话框消失**/
	public static void  dismissCreateDialog(){
		if(null !=mDialog && mDialog.isShowing()){
			mDialog.dismiss() ;
			mDialog = null ;
		}
	}

	/**
	 * 得到不同设备的uuid
	 * @param context 上下文对象
	 * @return
	 */
	public static String getMyUUID(Context context) {

		final TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);   

		String tmDevice = "" + tm.getDeviceId();  

		String tmSerial = "" + tm.getSimSerialNumber();   

		String androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);   

		UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());   

		String uniqueId = deviceUuid.toString();

		Log.i("iii","uuid="+uniqueId);

		return uniqueId;
	}
	/**
	 * 判断两次输入的密码是不是一致的
	 * @param password1  第一次输入的密码
	 * @param repassword1  第二次输入的密码
	 * @param context  上下文对象
	 * @return
	 */
	public static boolean accordance(String password1, String repassword1,Context context) {
		if(!password1.isEmpty()&!repassword1.isEmpty()){
			if(!password1.equals(repassword1)){
				Toast.makeText(context, "两次密码不一致，请重新输入", 1).show();
				return false;
			}
		}
		return true;
	}


	/**
	 * 对用户输入的密码进行MD5加密
	 * @param str 要加密的字符串
	 * @return
	 */

	public static  String Md5(String str) {

		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10) hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}


	/**
	 * 给textView设置不同的背影色 标签时使用
	 * @param text
	 * @param tv
	 */
	
	public static void setColor(String text,TextView tv,Context context){
		if("HR".equals(text)){
			tv.setBackgroundColor(context.getResources().getColor(R.color.hr_color)) ;
		}else if("TD".equals(text)){
			tv.setBackgroundColor(context.getResources().getColor(R.color.td_color)) ;
		}else if("GTU".equals(text)){
			tv.setBackgroundColor(context.getResources().getColor(R.color.gtu_color)) ;
		}else if("INNO".equals(text)){
			tv.setBackgroundColor(context.getResources().getColor(R.color.inno_color)) ;
		}else if("OPS".equals(text)){
			tv.setBackgroundColor(context.getResources().getColor(R.color.ops_color)) ;
		}else if("CS".equals(text)){
			tv.setBackgroundColor(context.getResources().getColor(R.color.cs_color)) ;
		}else if("FIN".equals(text)){
			tv.setBackgroundColor(context.getResources().getColor(R.color.fin_color)) ;
		}else if("COMM".equals(text)){
			tv.setBackgroundColor(context.getResources().getColor(R.color.comm_color));
		}
	}

	/**
	 * 取得拼音的缩写并转化成大写 标签时使用
	 * @param inputString
	 * @return
	 */
	public static String getAbbreviation(String inputString){
		String outPutString = null ;
		if("Technical Development".equals(inputString)){
			outPutString = "TD" ;
		}else if("Human Resources".equals(inputString)){
			outPutString = "HR" ;
		}else if("Trade Union".equals(inputString)){
			outPutString = "GTU" ;
		}else if("Innovation".equals(inputString)){
			outPutString = "INNO" ;
		}else if("Center Operations".equals(inputString)){
			outPutString = "OPS" ;
		}else if("Corporate Sustainability".equals(inputString)){
			outPutString = "CS" ;
		}else if("Finance".equals(inputString)){
			outPutString = "FIN" ;
		}else if("Communications".equals(inputString)){
			outPutString = "COMM" ;
		}
		return outPutString ;
	}

	/**
	 * 时间戳转换成时间
	 * @param a
	 * @return
	 */
	public static String getDateToStringt(int a) {
		Date d = new Date(a);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
		return sf.format(d);
	}

	/**
	 * 将数据保存在sd卡中
	 * @param str
	 */
	public static void saveToSd(Context context, String username,String  user_info_list)  {
		FileOutputStream fos=null;
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			File sdCardDir = Environment.getExternalStorageDirectory();
			File f=new File(sdCardDir,"abc.txt");
			if(!f.exists()){
				try {
					f.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}	
			try {
				fos = new FileOutputStream(f,true);
				String txt = username+"/"+user_info_list;
				fos.write(txt.toString().getBytes());
				fos.flush();
				fos.close();
				Log.i("eee", "写入SD卡成功");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static  void saveToSd2(Context context, String password)  {
		FileOutputStream fos=null;
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			File sdCardDir = Environment.getExternalStorageDirectory();
			File f=new File(sdCardDir,"info.txt");
			if(!f.exists()){
				try {
					f.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}	
			try {
				fos = new FileOutputStream(f,true);
				String txt = password;
				StringBuffer sb = new StringBuffer(txt); 
				fos.write(sb.append("-----").toString().getBytes());
				fos.flush();
				fos.close();
				Log.i("eee", "写入SD卡成功");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 从SD卡读数据
	 * @return
	 */
	public static  Map<String,String> getUserInfo(Context context,String namestr) {
		File file = new File(Environment.getExternalStorageDirectory(),"abc.txt");
		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			String str = br.readLine();
			String[] infos = str.split("/");
			Map<String,String> map = new HashMap<String, String>();
			Log.i("eee", "infos[0]"+infos[0]);
			Log.i("eee", "infos[1]"+infos[1]);
			map.put("username"+namestr, infos[0]);
			map.put("user_info_list"+namestr, infos[1]);
			return  map;
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getUserInfo2(Context context) {
		File file = new File(Environment.getExternalStorageDirectory(),"abc.txt");
		String str =null;
		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			str = br.readLine();
			Log.i("eee", "str是"+str);
		} catch(Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	/**
	 * 通过map的键来判断得到的值
	 * @param map
	 * @param name
	 * @return
	 */
	public static String readFromMap(Map<String, String> map,String name) {
		for(Entry<String, String> entry:map.entrySet()){
			Entry<String, String> n2 = entry;
			System.out.println("entry的键值是:"+n2.getKey()+"entry的值是"+n2.getValue());
			if(n2.getKey().equals(name)){
			Log.i("eee","map是"+ map.toString());
				Log.i("eee", "n2.getKey()是"+n2.getKey());
				return n2.getValue();
			}
		}
		return null;
	}


	private String spilt(String infos12) {
		String[] str = infos12.split("-----");
		for (String string : str) {
			String str_final = string;
			if(str_final.equals("hello2")){
				return str_final;  
			}
		}
		return null;	

	}













}
